<!-- 陈坤鹏 -->
<template>
  <div>
    <el-card shadow="hover" style="height: 200px">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">

        <el-row>
          <el-col :span="5">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="ruleForm.supplierId" placeholder="请选择">
                <el-option
                  v-for="item in supplierListOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="应退金额" prop="payable">
              <el-input v-model="ruleForm.amountPayable" disabled="disabled"/>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="实退金额" prop="paid">
              <el-input v-model="ruleForm.amountPaid"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="退货日期" prop="date">
              <el-date-picker v-model="ruleForm.returnDate" type="date" placeholder="选择时间" format="yyyy-MM-dd"
                              style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="5">
            <el-form-item label="退货单号" prop="returnNumber">
              <el-input v-model="ruleForm.returnNumber" disabled="disabled"/>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="ruleForm.remarks"/>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="是否退款" prop="isPaid">
              <el-select v-model="ruleForm.isPaid" placeholder="请选择">
                <el-option label="未退款" :value="2"/>
                <el-option label="已退款" :value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item style="float: right">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>

      </el-form>
    </el-card>
    <el-table
      :data="this.ruleForm.tableData.filter(data => !search
      || data.name.toLowerCase().includes(search.toLowerCase())
      || data.date.toLowerCase().includes(search.toLowerCase()))"
      height="500"
      style="width: 100%">
      <el-table-column>

        <el-table-column label="商品编码" prop="code"/>

        <template slot="header" slot-scope="scope">
          <el-button size="mini" type="primary"
                     class="el-icon-circle-plus-outline"
                     @click="returnGoods()"
                     style="float: left"> 添加

          </el-button>
        </template>

      </el-table-column>

      <el-table-column>
        <el-table-column label="商品名称" prop="name"/>
        <el-table-column label="商品型号" prop="model"/>
        <el-table-column label="商品单位" prop="unit"/>
        <el-table-column label="单价" prop="price"/>
        <el-table-column label="数量" prop="num"/>
        <el-table-column label="总金额" prop="total"/>
        <el-table-column align="right">

          <template slot="header" slot-scope="scope">
            <el-input v-model="search" size="mini" placeholder="输入关键字搜索"/>
          </template>

          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>

        </el-table-column>

      </el-table-column>
    </el-table>

    <el-dialog title="退货出库商品选择" :visible.sync="dialogTableVisible">
      <el-table :data="gridData">
        <el-table-column property="code" label="商品编码"/>
        <el-table-column property="name" label="商品名称"/>
        <el-table-column property="model" label="商品型号"/>
        <el-table-column property="unit" label="单位"/>
        <el-table-column property="lastPurchasingPrice" label="上次进价"/>
        <el-table-column property="purchasingPrice" label="成本均价"/>
        <el-table-column property="inventoryQuantity" label="库存数量"/>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="loadSaleProductList(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination align='center'
                     :current-page="page"
                     :page-sizes="[5,10,20,100]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-dialog>

    <el-dialog title="修改商品信息" :visible.sync="update">
      <el-form ref="form" :data="form" label-width="100px">
        <el-form-item label="商品编码">
          <el-input v-model="form.code" width="20" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="form.name" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="商品型号">
          <el-input v-model="form.model" width="20" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="商品单位">
          <el-input v-model="form.unit" width="20" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="form.price" width="20"/>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="form.num"/>
        </el-form-item>
        <el-form-item label="总金额" style="visibility: hidden">
          <el-input v-model="form.total"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="" @click="update=false">取消</el-button>
        <el-button type="" @click="FormUpdate()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

export default {
  data() {
    return {
      supplierListOptions: [],
      dialogTableVisible: false,
      tableData: [],
      gridData: [],
      form: {},
      pageSize: 5,
      page: 1,
      total: 0,
      update: false,
      brandListOptions: [],
      search: '',
      ruleForm: {
        returnNumber: '',
        tableData: [],
        amountPayable: 0,
        amountPaid: 0,
        returnDate: '',
        remarks: '',
        isPaid: null,
        supplierId: null
      },
      rules: {
        supplierId: [
          {type: 'number', required: true, message: '请选择供应商', trigger: 'blur'},
        ],
        amountPayable: [
          {required: true, message: '请输入应退金额', trigger: 'blur'},
        ],
        amountPaid: [
          {required: true, message: '请输入实退金额', trigger: 'blur'},
        ],
        purchaseDate: [
          {type: 'date', required: true, message: '请输入日期', trigger: 'blur'},
        ],
        remarks: [
          {message: '请输入备注', trigger: 'blur'},
        ],
        isPaid: [
          {type: 'number', required: true, message: '请选择是否退款', trigger: 'blur'},
        ]
      }
    };
  },
  methods: {
    sum() {
      this.form.total = this.form.price * this.form.num;
    },
    loadSaleProductList(row) {
      for (let i = 0; i < this.ruleForm.tableData.length; i++) {
        let product = this.ruleForm.tableData[i];
        if (product.id == row.id) {
          return;
        }
      }
      this.ruleForm.tableData.push(row);
      console.log(this.ruleForm.tableData);
      this.dialogTableVisible = false;
    },
    returnGoods() {
      let url = 'http://localhost:8887/goods/getHasInventoryQuantity';
      console.log('url = ' + url);
      this.axios
        .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
        .get(url).then((response) => {
        let responseBody = response.data.data;
        this.gridData = responseBody;
        this.dialogTableVisible = true;
      });
    },
    countAmountPayable() {
      let sum = 0;
      let tableData = this.ruleForm.tableData;
      for (let i = 0; i < tableData.length; i++) {
        sum = sum + tableData[i].total
      }
      this.ruleForm.amountPayable = sum;
      console.log(this.ruleForm.amountPayable);
    },
    date() {
      const now = new Date();
      const year = now.getFullYear(); //得到年份
      let month = now.getMonth(); //得到月份
      let date = now.getDate(); //得到日期
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      return new Date(`${year}-${month}-${date}`);
    },
    handleEdit(index, row) {
      this.form = row;
      this.update = true;
    },
    FormUpdate() {
      this.sum();
      this.countAmountPayable();
      this.update = false;
    },
    handleDelete(ReturnGoods, row) {
      console.log(ReturnGoods, row);
      let message = '是否删除此退货商品';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ruleForm.tableData.splice(ReturnGoods, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    backToPreStep() {
      this.$router.push('spu-add-new');
    },
    loadBrandList() {
      let url = 'http://localhost:8887/brands';
      console.log('url = ' + url);
      this.axios
        .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
        .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.brandListOptions = responseBody.data;
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.tableData == false) {
            this.$notify({
              title: '警告',
              message: '尚未选择进货商品',
              type: 'warning'
            });
            return;
          }
          console.log(this.ruleForm);
          let url = 'http://localhost:8887/returnListGoods/save';
          console.log('url = ' + url);
          // let stringify = this.qs.stringify(this.tableData);
          // console.log(stringify);
          this.axios
            .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
            .post(url, this.ruleForm).then((response) => {
            console.log(this.ruleForm)
            let responseBody = response.data;
            console.log(responseBody);
            /*if (responseBody.state == 20000) {
              this.ruleForm.brandName = responseBody.data.name;
              let ruleFormString = JSON.stringify(this.ruleForm);
              console.log('ruleFormString >>> ' + ruleFormString);
              localStorage.setItem('ruleForm', ruleFormString);
              this.$router.push('spu-add-new3');
            } else {
              this.$message.error(responseBody.message);
            }*/

          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    setDialogTableVisible() {
      this.dialogTableVisible = true;
      let url = 'http://localhost:8887/goods/list';
      this.axios
        .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
        .get(url).then((response) => {
        let responseBody = response.data;
        console.log(responseBody)
        this.ruleForm.tableData = responseBody.data;
        /*if (responseBody.state == 20000) {
          this.brandListOptions = responseBody.data;
        } else {
          this.$message.error(responseBody.message);
        }*/
      });
    },
    supplierList() {
      let url = 'http://localhost:8887/supplier/getComboboxList';
      this.axios
        .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
        .get(url).then((response) => {
        let responseBody = response.data;
        this.supplierListOptions = responseBody.data;
        console.log(this.supplierListOptions)
        this.countAmountPayable();
      });
    },
    getReturnNumber() {
      let url = 'http://localhost:8887/returnListGoods/getNum';
      this.axios
        .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
        .get(url).then((response) => {
        let responseBody = response.data;
        console.log(responseBody);
        this.ruleForm.returnNumber = responseBody.data;
        console.log(this.ruleForm.returnNumber);
      });
    }
  },
  mounted() {
    this.getReturnNumber();
    this.ruleForm.purchaseDate = this.date();
    this.supplierList();
    this.countAmountPayable();
  }
}
</script>
